package com.mobis.user.service;

import com.mobis.user.dao.UserDao;
import com.mobis.user.pojo.User;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.IdWorker;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public void saveUser(User user){

        user.setId( idWorker.nextId()+"" );
        user.setFollowcount(0);//关注数
        user.setFanscount(0);//粉丝数
        user.setOnline(0L);//在线时长
        user.setRegdate(new Date());//注册日期
        user.setUpdatedate(new Date());//更新日期
        user.setLastdate(new Date());//最后登陆日期
        //对密码进行加密
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userDao.save(user);
    }



    public void sendSms(String mobile){
        String checkCode= RandomStringUtils.randomNumeric(4);
        System.out.println(checkCode+"==============");
        //redies缓存中存一分
        redisTemplate.opsForValue().set("check_"+checkCode,checkCode,5, TimeUnit.MINUTES);
        //发送到用户手机一分,先发送到rabbitmq
        Map<String ,String> map=new HashMap<>();
        map.put("mobile",mobile);
        map.put("check",checkCode);
        rabbitTemplate.convertAndSend("mobis",map);

        //日志打印一分
        System.out.println("发送的验证码为："+checkCode);
    }

    public User loginUser(User user){
        User user1=userDao.findByMobile(user.getMobile());

        if (null==user1||!bCryptPasswordEncoder.matches(user.getPassword(),user1.getPassword())){
            return null;
        }
        return user1;
    }

    public void deleteById(String id){
        userDao.deleteById(id);
    }

    @Transactional
    public void incFansCount(int x,String userid){
        userDao.updatefanscount(x,userid);
    }
    @Transactional
    public void incFollowCount(int x,String userid){
        userDao.updatefollowcount(x,userid);
    }

}
